// UpdaterModule.cs
//
// Copyright (c) 2007 Mike Strobel
//
// This source code is subject to the terms of the Microsoft Reciprocal License (Ms-RL).
// For details, see <http://www.opensource.org/licenses/ms-rl.html>.
//
// All other rights reserved.

using System;

using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using Supremacy.Annotations;
using Supremacy.Client;

namespace Supremacy.Updater
{
    public class UpdaterModule : IModule
    {
        private readonly IUnityContainer _container;
        private readonly IRegionViewRegistry _regionViewRegistry;
        private readonly IClientApplication _clientApplication;
        private IUpdaterService _updaterService;

        public UpdaterModule(
            [NotNull] IUnityContainer container,
            [NotNull] IRegionViewRegistry regionViewRegistry,
            [NotNull] IClientApplication clientApplication)
        {
            if (container == null)
                throw new ArgumentNullException("container");
            if (regionViewRegistry == null)
                throw new ArgumentNullException("regionViewRegistry");
            if (clientApplication == null)
                throw new ArgumentNullException("clientApplication");
            _container = container;
            _regionViewRegistry = regionViewRegistry;
            _clientApplication = clientApplication;
        }

        #region Implementation of IModule
        public void Initialize()
        {
            if (_clientApplication.CommandLineArguments.DisableUpdates)
                return;
            RegisterViewsAndServices();
        }
        #endregion

        private void EnsureUpdater()
        {
            if (_updaterService == null)
                _updaterService = _container.Resolve<IUpdaterService>();
        }

        private void RegisterViewsAndServices()
        {
            _container.RegisterType<IUpdaterService, UpdaterService>(new ContainerControlledLifetimeManager());
            _container.RegisterType<UpdaterOptionsPage>(new ContainerControlledLifetimeManager());
            _regionViewRegistry.RegisterViewWithRegion(ClientRegions.OptionsPages, typeof(UpdaterOptionsPage));

            EnsureUpdater();

            if (UpdaterSettings.GetCheckForUpdatesOnStartup(ClientSettings.Current))
                _updaterService.CheckForUpdates();
        }
    }
}